import 'package:hotfil_pub_web/pages/login/pass_login.dart';
import 'package:hotfil_pub_web/routes/app_pages.dart';
import 'package:hotfil_pub_web/shared/aes.dart';
import 'package:hotfil_pub_web/shared/http/http.dart';
import 'package:hotfil_pub_web/shared/sputils.dart';
import 'package:get/get.dart';

class LoggedInUser {
  String? userId;
  String? type;

  LoggedInUser({this.userId, this.type});

  factory LoggedInUser.fromJson(Map<String, dynamic> json) => LoggedInUser(
        userId: json['userId'] as String?,
        type: json['type'] as String?,
      );

  Map<String, dynamic> toJson() => {
        'userId': userId,
        'type': type,
      };
}

class LoginRes {
  String accessToken;
  int? accessExpiresIn;
  String? refreshToken;
  int? refreshExpiresIn;
  LoggedInUser? loggedInUser;

  LoginRes({
    this.accessToken = '',
    this.accessExpiresIn,
    this.refreshToken,
    this.refreshExpiresIn,
    this.loggedInUser,
  });

  factory LoginRes.fromJson(Map<String, dynamic> json) => LoginRes(
        accessToken: json['accessToken'] as String,
        accessExpiresIn: json['accessExpiresIn'] as int?,
        refreshToken: json['refreshToken'] as String?,
        refreshExpiresIn: json['refreshExpiresIn'] as int?,
        loggedInUser: json['loggedInUser'] == null
            ? null
            : LoggedInUser.fromJson(
                json['loggedInUser'] as Map<String, dynamic>),
      );

  Map<String, dynamic> toJson() => {
        'accessToken': accessToken,
        'accessExpiresIn': accessExpiresIn,
        'refreshToken': refreshToken,
        'refreshExpiresIn': refreshExpiresIn,
        'loggedInUser': loggedInUser?.toJson(),
      };
}

passLoginApi({countryCode = "86", phone, String password = ''}) async {
  var res = await Https().post('/auth/login', data: {
    "countryCode": countryCode,
    "phone": phone,
    "password": cryptoAES(message: password),
  });
  var loginres = LoginRes.fromJson(res['data']);
  print(loginres.accessToken);
  SpUtil().setStr('token', loginres.accessToken);
  Get.offAndToNamed(Routes.DASHBOARD);

  return loginres;
}
